package m.jclecai.com.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;

import java.util.ArrayList;
import java.util.List;

import m.jclecai.com.R;
import m.jclecai.com.utils.BitmapUtil;
import m.jclecai.com.utils.ScreenUtil;

/**
 * Created by ZD on 2017/6/23.
 * 三个骰子分别处理
 * 骰子移动的时候将上一个坐标x y值作为下一个坐标的起始坐标
 */

public class DiceView extends FrameLayout {

    List<ImageView> imageViews;
    float[] toOnePosition = null;
    float[] toTwoPosition = null;
    float[] toThreePosition = null;
    int animationCount = 6;
    boolean animationEnd = false;
    MediaPlayer player;

    public DiceView(Context context) {
        super(context);
        init();
    }

    public DiceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public DiceView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    int screenWidth, screenHeight, width, split, leftMargin, topMargin;

    void init() {
        toOnePosition = new float[2];
        toTwoPosition = new float[2];
        toThreePosition = new float[2];
        screenWidth = getResources().getDisplayMetrics().widthPixels;
        screenHeight = getResources().getDisplayMetrics().heightPixels;
        width = ScreenUtil.dip2px(getContext(), 80);
        split = ScreenUtil.dip2px(getContext(), 10);
        //减去骰子的大小和中间间距
        leftMargin = (screenWidth - width * 2 - split) / 2;
        topMargin = (screenHeight - width * 2 - split) / 2;
        imageViews = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            ImageView img = new ImageView(getContext());
            imageViews.add(img);
            LayoutParams layoutParams = new LayoutParams(width, width);
            if (i == 0) {
                layoutParams.topMargin = topMargin - width;
                layoutParams.leftMargin = leftMargin;
            } else if (i == 1) {
                layoutParams.topMargin = topMargin - width;
                layoutParams.leftMargin = leftMargin + split + width;
            } else {
                layoutParams.topMargin = topMargin + split;
                layoutParams.leftMargin = leftMargin + (width + split) / 2;
            }
            img.setLayoutParams(layoutParams);
            img.setImageResource(R.drawable.dice_animlist);
            AnimationDrawable animationDrawable = (AnimationDrawable) img.getDrawable();
            animationDrawable.start();
            addView(img);
        }
        startTransAnimation();
        startMp3(R.raw.b);
    }

    public void reStartTransAnimation() {
        if (!animationEnd) return;
        animationEnd = false;
        animationCount = 11;
        removeAllViews();
        init();
    }

    void startTransAnimation() {
        startTransAnimation(false);
    }

    void startTransAnimation(boolean reset) {
        //获取不超过屏幕范围的随机坐标
        float[] positionX = getViewPosition(toOnePosition[0], -leftMargin, reset);
        float[] positionY = getViewPosition(toOnePosition[1], -topMargin, reset);
        //交换起始坐标
        toOnePosition[0] = positionX[1];
        toOnePosition[1] = positionY[1];
        imageViews.get(0).startAnimation(getTransAnimation(0, 100,
                positionX[0], positionX[1], positionY[0], positionY[1]));
        //获取不超过屏幕范围的随机坐标
        positionX = getViewPosition(toTwoPosition[0], leftMargin, reset);
        positionY = getViewPosition(toTwoPosition[1], -topMargin, reset);
        //交换起始坐标
        toTwoPosition[0] = positionX[1];
        toTwoPosition[1] = positionY[1];
        imageViews.get(1).startAnimation(getTransAnimation(1, 100
                , positionX[0], positionX[1], positionY[0], positionY[1]));
        //获取不超过屏幕范围的随机坐标
        positionX = getViewPosition(toThreePosition[0], leftMargin + (width + split) / 2, reset);
        positionY = getViewPosition(toThreePosition[1], topMargin - split - width, reset);
        //交换起始坐标
        toThreePosition[0] = positionX[1];
        toThreePosition[1] = positionY[1];
        imageViews.get(2).startAnimation(getTransAnimation(2, 100,
                positionX[0], positionX[1], positionY[0], positionY[1]));
    }

    float[] getViewPosition(float fromDelta, float toDelta, boolean reset) {
        //做一个随机数来进行 模拟来回弹动坐标 例如坐标-1 1
        if (System.currentTimeMillis() % 2 == 0)
            toDelta = Math.abs(toDelta);
        float[] position = new float[2];
        float to = (float) (Math.random() * (toDelta - fromDelta) + fromDelta);
        position[0] = fromDelta;
        if (Math.abs(to) > width)//如果随机数小于骰子宽度则两个相加
            position[1] = to < 0 ? to + width : to - width;
        else
            position[1] = to;
        if (reset) {//重置骰子位置
//            position[0] = 0;
            position[1] = 0;
        }
        return position;
    }

    TranslateAnimation getTransAnimation(final int index, int duration, float fromXDelta, float toXDelta, float fromYDelta, float toYDelta) {
        TranslateAnimation animation = new TranslateAnimation(fromXDelta, toXDelta, fromYDelta, toYDelta);
        animation.setInterpolator(new LinearInterpolator() {
            @Override
            public float getInterpolation(float input) {
                if (animationCount == -1) {//动画结束后 往对应容器缩小靠拢
                    if (index == 1) {
                        float scale = imageViews.get(0).getScaleX();
                        if (scale <= input && scale == 1) {
                            scale = input;
                        } else {
                            scale = 1 - input;
                        }
                        imageViews.get(0).setScaleX(scale);
                        imageViews.get(0).setScaleY(scale);
                        imageViews.get(1).setScaleX(scale);
                        imageViews.get(1).setScaleY(scale);
                        imageViews.get(2).setScaleX(scale);
                        imageViews.get(2).setScaleY(scale);
                    }
                }
                return super.getInterpolation(input);
            }
        });
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                Log.e("getViewPosition", index + "_" + animationCount);
                if (index == 0 && animationCount == 1) {//重置动画
                    animationCount--;
                    startTransAnimation(true);
                } else if (index == 0 && animationCount > 1) {//循环调用动画
                    animationCount--;
                    startTransAnimation();
                } else if (index == 0 && animationCount == 0) {
                    animationCount--;
                    List<Integer> values = callback.diceValues();
                    //动画结束后 往对应容器缩小靠拢
                    imageViews.get(0).setImageResource(BitmapUtil.getResIdByFolder(getContext(), "shaizi_" + values.get(0), "drawable"));
                    imageViews.get(1).setImageResource(BitmapUtil.getResIdByFolder(getContext(), "shaizi_" + values.get(1), "drawable"));
                    imageViews.get(2).setImageResource(BitmapUtil.getResIdByFolder(getContext(), "shaizi_" + values.get(2), "drawable"));
                    postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            List<Rect> rects = getViewPosition(callback.moveToView());
                            Rect rec = rects.get(0);
                            //摇骰子动画结束后的 缩小位移阶段动画
                            imageViews.get(0).startAnimation(getTransAnimation(0, 500,
                                    0,
                                    (rec.right - leftMargin - width),
                                    0,
                                    (rec.bottom - topMargin - width / 2 + rec.height() / 2)));
                            rec = rects.get(1);
                            imageViews.get(1).startAnimation(getTransAnimation(1, 500,
                                    0,
                                    (rec.right - leftMargin - width - rec.width() * 3 / 2),
                                    0,
                                    (rec.bottom - topMargin - width / 2 + rec.height() / 2)));//- width
                            rec = rects.get(2);
                            imageViews.get(2).startAnimation(getTransAnimation(2, 500,
                                    0,
                                    (rec.right - leftMargin - width - rec.width() / 2),
                                    0,
                                    (rec.bottom - topMargin - width - rec.height() / 2)));
                        }
                    }, 300);
                    player.pause();
                } else if (index == 1 && animationCount == -1) {
                    animationEnd = true;
                    callback.complete();
                    startMp3(R.raw.a);
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        animation.setDuration(duration);
        return animation;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }

    public interface Callback {
        List<View> moveToView();

        List<Integer> diceValues();

        void complete();
    }

    //获取view的位置大小
    List<Rect> getViewPosition(List<View> views) {
        List<Rect> recs = new ArrayList<>();
        for (int i = 0; i < views.size(); i++) {
            Rect rc = new Rect();
            views.get(i).getGlobalVisibleRect(rc);
            recs.add(rc);
        }
        return recs;
    }

    Callback callback;

    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    void startMp3(int resId) {
        if (player != null) {
            player.stop();
            player.reset();
            player.release();
            player = null;
        }
        player = MediaPlayer.create(getContext(), resId);
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        player.start();
    }
}
